package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.dao.CoursesDao;
import model.dao.TeacherDao;
import model.dao.Teacher_CourseDao;
import model.entity.Teacher;

/**
 * Servlet implementation class GetTeacher
 */
@WebServlet("/GetTeacher")
public class GetTeacher extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetTeacher() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		boolean isSave = true;
		List<Object> tCList = null, listTName = new ArrayList<>();
		listTName.clear();
		String str = null;
		String courVal = (String)request.getParameter("text2");
		String[] courValArray = courVal.split(",");
		HttpSession session = request.getSession(true);
		session.setAttribute("courseArray", courValArray);
		CoursesDao courdao = new CoursesDao();
		Teacher_CourseDao tCDao = new Teacher_CourseDao();
		TeacherDao teacher = new TeacherDao();
		Object id = new String("id");
		Object name = new String("name");
		Object teacherid = new String("teacher_id");
		for (String courName : courValArray) {
			List<Object> list = courdao.getSigleSelect(id, name, courName);
			Object courseid = new String("course_id");
			for (int i = 0; i < list.size(); i++) {
				tCList = tCDao.getSigleSelect(teacherid, courseid, list.get(i));
			}

			for (Object teaid : tCList) {
				List<Object> teacherName = teacher.getSigleSelect(name, id, teaid);
				for (Object object : teacherName) {
					for (Object val : listTName) {
						if (object.equals(val)) {
							isSave = false;
							break;
						}
					}
					if (isSave) {
						listTName.add(object);
					}
					isSave = true;
				}
			}
		}
		str = "[";
		for (Object object1 : listTName) {
			str += "{\"name\":\"" + (String) object1 + "\"},";
		}
		str = str.substring(0, str.length() - 1);
		str += "]";
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(str);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
